const Error = require('../config/error-code')
const config = require('../config')
const { User, App, User_BackUp } = require('../model')
const { formatTime } = require('../utils/date')
const path = require('path')

exports.getUserbackupData = async (req, res, next) => {
    // 获取用户的备份数据
    try
    {
        let _id = req.user._id
        const data = await User_BackUp.find({ creater:_id })
        if (data.length)
        {
            let appIds = [];
            let appData = Array.from(data[0].appList)
            appData.forEach((item) => {
                if (item.children)
                {
                    appIds.push(...item.children)
                    return;
                }
                appIds.push(item)
            })
            const appFullData = await App.find({_id:{$in:appIds}})

            // 填充完整数据
            for(let i = 0; i < appFullData.length; i++)
            {
                for (let k = 0; k < appData.length; k++)
                {
                    if (appData[k].children)
                    {
                        let childIndex = appData[k].children.indexOf(appFullData[i].id)
                        if (childIndex >= 0)
                        {
                            appData[k].children[childIndex] = appFullData[i]
                        }
                    }
                    if(appFullData[i].id === appData[k])
                    {
                        appData[k] = appFullData[i]
                    }
                }
            }
            // console.log(appData);
            data[0].appList = appData;
        }
        else
        {
            let backup = new User_BackUp()
            backup.creater = _id
            // backup.type = '0'
            await backup.save()
            data.push(backup.toJSON())
        }
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{
                content:data
            }
        })
    }
    catch (err)
    {
        next(err)
    }
}

exports.updateApp = async (req, res, next) => {
    try
    {
        let { id, inc } = req.body
        await App.findByIdAndUpdate(id, { $inc: { hot:inc } })
        res.status(200).json({
            success:true
        })
    }
    catch (err)
    {
        next(err)
    }
}

exports.backupUserAppData = async (req, res, next) => {
    try
    {
        let userId = req.user._id;
        let { backupId, data, type } = req.body
        if (backupId.trim() !== '')
        {
            // 备份的id存在 更新
            await User_BackUp.findByIdAndUpdate(backupId,{updatedAt:formatTime(), appList:data})
        }
        else
        {
            // 新增
            let backup = new User_BackUp()
            backup.creater = userId;
            backup.type = type;
            backup.appList = data;
            await backup.save();
        }
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{}
        })
    }
    catch (err)
    {
        next(err)
    }
}

exports.backupUserData = async (req, res, next) => {
    try
    {
        let userId = req.user._id;
        let { backupId, data, type } = req.body
        if (backupId.trim() !== '')
        {
            // 备份的id存在 更新
            const backup = await User_BackUp.findById(backupId)
            backup['updatedAt'] = formatTime()
            backup[type] = data
            await backup.save()
        }
        else
        {
            return res.status(200).json({
                success:false,
                errcode:Error['XP050'].errcode,
                errmsg:Error['XP050'].errmsg,
                data:{}
            })
        }
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{}
        })
    }
    catch (err)
    {
        next(err)
    }
}

exports.getDataByTag = async (req, res, next) => {
    try
    {
        let { type, tag } = req.query
        let data = null;
        if (type === 'island')
        {
            if (tag === '热门')
            {
                data = await App.find({ isIsland:true,isShow:true }).sort({hot:-1, createdAt:-1}).limit(30)
            }
            else
            {
                let filter = {
                    $and:[
                        { isIsland:true },
                        { tag: { $elemMatch:{ $eq: tag } } },
                        { isShow:true }
                    ]
                }
                data = await App.find(filter).sort({createdAt:-1}).limit(30)
            }
            return res.status(200).json({
                success:true,
                errcode:"",
                errmsg:"",
                data:{
                    content:data
                }
            });
        }
        if (tag === '热门')
        {
            data = await App.find({ type:{ $in:type },isShow:true }).sort({hot:-1, createdAt:-1}).limit(30)
        }
        else
        {
            let filter = {
                $and:[
                    { type:{ $in:type } },
                    { tag: { $elemMatch:{ $eq: tag } } },
                    { isShow:true }
                ]
            }
            data = await App.find(filter).sort({createdAt:-1}).limit(30)
        }
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{
                content:data
            }
        })
    }
    catch (err)
    {
        next(err)
    }
}

exports.searchData = async (req, res, next) => {
    try
    {
        let { search, type } = req.query
        let filter = {}
        if (type === 'island')
        {
            filter = {
                $and:[
                    { isIsland:true },
                    { name:{ '$regex': search, '$options': 'si' }},
                    { isShow:true }
                ]
            }
        }
        else
        {
            filter = {
                $and:[
                    { type:{ $in:type } },
                    { name:{ '$regex': search, '$options': 'si' }},
                    { isShow:true }
                ]
            }
        }
        let data = await App.find(filter).sort({createdAt:-1, hot:-1}).limit(30)
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{
                content:data
            }
        })
    }
    catch (err)
    {
        next(err)
    }
}

exports.getData = async (req, res, next) => {
    try
    {
        // 获取每项的前三十个数据
        let data = await App.find({type:'web',isShow:true}).sort({createdAt:-1}).limit(30)
        let data1 = await App.find({type:{$ne:'web'},isShow:true}).sort({createdAt:-1}).limit(30)
        // let data2 = await App.find({isIsland:true,isShow:true}).sort({createdAt:-1}).limit(30)
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{
                content:data.concat(data1)
            }
        })
    }
    catch (err)
    {
        next(err)
    }
}

exports.getDataByPage = async (req, res, next) => {
    try
    {
        let { type, tag, skip } = req.query
        let limit = 30
        let data = null;
        if (type === 'island')
        {
            if (tag === '热门')
            {
                data = await App.find({ isIsland:true,isShow:true }).sort({hot:-1, createdAt:-1}).limit(limit).skip(Number(skip))
            }
            else
            {
                let filter = {
                    $and:[
                        { isIsland:true },
                        { tag: { $elemMatch:{ $eq: tag } } },
                        { isShow:true }
                    ]
                }
                data = await App.find(filter).sort({createdAt:-1}).limit(limit).skip(Number(skip))
            }
        }
        else
        {
            if (tag === '热门')
            {
                data = await App.find({ type:{ $in:type },isShow:true }).sort({hot:-1, createdAt:-1}).limit(limit).skip(Number(skip))
            }
            else
            {
                let filter = {
                    $and:[
                        { type:{ $in:type } },
                        { tag: { $elemMatch:{ $eq: tag } } },
                        { isShow:true }
                    ]
                }
                data = await App.find(filter).sort({createdAt:-1}).limit(limit).skip(Number(skip))
            }
        }
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{
                content:data
            }
        })
    }
    catch (err)
    {
        next(err)
    }
}

exports.getAppTags = async (req, res, next) => {
    res.status(200).json({
        success:true,
        errcode:"",
        errmsg:"",
        data:{
            content:config.appTag
        }
    })
}

exports.previewIcon = (req, res, next) => {
    try {
        let rootPath = path.resolve(__dirname,'../')
        return res.sendFile(rootPath + `/upload/icon/${encodeURIComponent(req.params.name)}`);
    } catch (err) {
        next(err)
    }
}


exports.addApp = async (req, res,next) => {
    try
    {
        let app = new App(req.body)
        await app.save()
        res.status(200).json({
            success:true,
            errcode:"",
            errmsg:"",
            data:{
                content:app
            }
        })
    }
    catch(err)
    {
        next(err)
    }
}